document.addEventListener("DOMContentLoaded", function () {
  const linksContainer = document.getElementById("linksContainer");
  const pasteButton = document.querySelector(".btns");
  // const deleteButton = document.querySelector('.btn2');
  const addButton = document.querySelector(".btn3");
  const parseButton = document.querySelector(".btn4");
  const inputField = document.querySelector(".input-btn");
  const platformSupport = document.querySelector(".platform-support");

  // 存储链接的数组
  let links = [];

  // 定义不同类型链接的最大数量限制
  const MAX_IMAGE_LINKS = 5;
  const MAX_VIDEO_LINKS = 10;

  // 获取支持平台列表
  function fetchPlatforms() {
    ajaxRequest({
      url: "/api/videoexport/support_list",
      method: "GET",
      success: function (response) {
        if (response && response.data) {
          renderPlatforms(response.data.rows);
        }
      },
      error: function (xhr, status, error) {
        console.error("获取平台列表失败:", error);
      },
    });
  }

  // 渲染平台列表
  function renderPlatforms(platforms) {
    platformSupport.innerHTML = "";
    platforms.forEach((platform) => {
      const platformDiv = document.createElement("div");
      platformDiv.className = "pic";
      platformDiv.innerHTML = `
        <img src="https://get.215000.com${platform.icon_image}" >
        <div>${platform.name}</div>
      `;
      platformSupport.appendChild(platformDiv);
    });
  }

  // 页面加载时获取平台列表
  fetchPlatforms();
  sessionStorage.setItem("resources", "");

  // 粘贴链接按钮点击事件
  pasteButton.addEventListener("click", function () {
    navigator.clipboard
      .readText()
      .then((text) => {
        // 直接设置文本，保留原始格式
        inputField.value = text;
      })
      .catch((err) => {
        console.error("无法访问剪贴板:", err);
      });
  });

  // 一键解析按钮点击事件
  parseButton.addEventListener("click", function () {
    const inputText = inputField.value.trim();
    if (!inputText) {
      alert("请输入需要解析的链接！");
      return;
    }

    // 按换行符分割链接
    const links = inputText.split(/\r?\n/).filter((link) => link.trim());

    if (links.length === 0) {
      alert("请先添加需要解析的链接！");
      return;
    }

    // 检查链接数量限制
    // if (links.length > MAX_VIDEO_LINKS) {
    //   alert(`最多只能添加${MAX_VIDEO_LINKS}条视频链接！`);
    //   return;
    // }

    // 显示加载状态
    parseButton.disabled = true;
    parseButton.innerHTML = "<text>解析中...</text>";

    // 存储所有解析结果
    let allResults = [];
    let currentIndex = 0;

    // 递归函数处理每个链接的解析
    function parseNextLink() {
      if (currentIndex >= links.length) {
        // 所有链接解析完成
        parseButton.disabled = false;
        parseButton.innerHTML = "<text>一键解析</text>";

        // 存储所有解析结果
        sessionStorage.setItem("resources", JSON.stringify(allResults));
        console.log(allResults, "allResults");

        // 检查第一个链接的resType
        if (
          allResults.length > 0 &&
          allResults[0].data.res &&
          allResults[0].data.res.length > 0
        ) {
          const firstResType = allResults[0].data.res[0].resType;

          // 如果是图片类型，检查数量限制
          if (firstResType == "1") {
            if (links.length > MAX_IMAGE_LINKS) {
              alert(`图片类最多只能添加${MAX_IMAGE_LINKS}条链接！`);
              parseButton.disabled = false;
              parseButton.innerHTML = "<text>一键解析</text>";
              return;
            }
            window.location.href = "list2.html";
          } else {
            if (links.length > MAX_VIDEO_LINKS) {
              alert(`视频类最多只能添加${MAX_VIDEO_LINKS}条链接！`);
              parseButton.disabled = false;
              parseButton.innerHTML = "<text>一键解析</text>";
              return;
            }
            window.location.href = "list1.html";
          }
        }
        return;
      }

      const currentLink = links[currentIndex];

      // 调用解析接口
      ajaxRequest({
        url: "/api/videoexport/parse",
        method: "POST",
        data: {
          url: currentLink,
          device_id: "1111",
        },
        success: function (response) {
          if (response && response.code === 1) {
            // 解析成功，保存结果
            allResults.push({
              url: currentLink,
              data: response.data,
            });
            currentIndex++;
            parseNextLink();
          } else {
            alert(
              `链接 ${currentLink} 解析失败：${response?.message || "未知错误"}`
            );
            currentIndex++;
            parseNextLink();
          }
        },
        error: function (xhr, status, error) {
          console.error(`链接 ${currentLink} 解析请求失败:`, error);
          alert(`链接 ${currentLink} 解析请求失败，请重试！`);
          currentIndex++;
          parseNextLink();
        },
      });
    }

    // 开始解析第一个链接
    parseNextLink();
  });

  // 更新链接列表显示
  function updateLinksList() {
    linksContainer.innerHTML = "";
    links.forEach((link, index) => {
      const linkItem = document.createElement("div");
      linkItem.className = "link-item";
      linkItem.innerHTML = `
                <div class="link-content">
                    <span>${index + 1}. ${link}</span>
                    <button class="delete-link" data-index="${index}">删除</button>
                </div>
            `;
      linksContainer.appendChild(linkItem);
    });

    // 为每个删除按钮添加事件监听
    document.querySelectorAll(".delete-link").forEach((button) => {
      button.addEventListener("click", function () {
        const index = parseInt(this.getAttribute("data-index"));
        links.splice(index, 1);
        updateLinksList();
      });
    });
  }

  $(document).ready(function () {
    const $linkInput = $("#linkInput");
    const $linkCount = $(".link-count");

    function updateLinkCount() {
      const text = $linkInput.val();
      const lines = text.split("\n").filter((line) => line.trim() !== "");
      const remainingLinks = MAX_VIDEO_LINKS - lines.length;
      $linkCount.text(`剩余链接数：${remainingLinks}`);

      if (remainingLinks < 0) {
        $linkCount.css("color", "red");
      } else {
        $linkCount.css("color", "#666");
      }
    }

    $linkInput.on("input", function () {
      const text = $(this).val();
      const lines = text.split("\n").filter((line) => line.trim() !== "");

      if (lines.length > MAX_VIDEO_LINKS) {
        const truncatedText = lines.slice(0, MAX_VIDEO_LINKS).join("\n");
        $(this).val(truncatedText);
      }

      updateLinkCount();
    });

    // 初始化显示
    updateLinkCount();
  });
});
